<template>
  <div>
 
   <div style="margin-bottom: 5px;">
    <div>
      <el-input v-model="userId" suffix-icon="el-icon-search" placeholder="请输入用户ID" style="width: 200px;" @keyup.enter.native="queryData"></el-input>
      <el-button  type="primary" style="margin-left: 10px;" @click="queryData">搜索</el-button>
      <el-button type="info" @click="reset" plain>重置</el-button>
    </div>
 
     <el-button  type="primary" style="margin: 10px;" @click="add" plain>新增</el-button>
     <el-button type="danger" @click="batchDelete" :disabled="this.sels.length === 0" plain>批量删除</el-button>
   </div>
 
   <el-table :data="tableData"
     :header-cell-style="{background:'#f2f5fc',color: '#555555',textAlign:'center'}"
     border
     @selection-change="handleSelectionChange"
     :row-key="getRowKeyOfTarget"
     :cell-style="{textAlign:'center'}"
     style="overflow-y: auto;height: calc(100vh - 152px);"
   >

         <!-- 选框 -->
         <el-table-column 
          type="selection" 
          width="40"
          :reserve-selection="true" 
        ></el-table-column>

         <el-table-column prop="userId" label="用户ID" width="60">
         </el-table-column>
 
         <el-table-column prop="userName" label="用户名" width="">
         </el-table-column>
 

         <el-table-column prop="address" label="地址" width="120">
         </el-table-column>
 
         <el-table-column prop="email" label="邮箱" >
         </el-table-column>
 
         <el-table-column prop="telephone" label="电话号码" >
         </el-table-column>

         <el-table-column label="状态">
          <template slot-scope="scope">
            <el-button :type="getStatusButtonClass(scope.row.status)" size="mini" style="border-radius: 10px;" plain @click="changeStatus(scope.row)">{{ scope.row.status }}</el-button>
          </template>
        </el-table-column>
 
         
         <el-table-column prop="created" label="创建时间" width="120px">
         </el-table-column>
 
         <el-table-column prop="updated" label="更新时间" >
         </el-table-column>
 
         <!-- <el-table-column label="头像">
            <template #default="scope">
               <img 
               :src="getAvatarUrl(scope.row.imgUrl)" 
               alt="用户头像" 
               style="width: 50px; height: 50px;">
            </template>
         </el-table-column> -->

         <el-table-column label="头像">
            <template #default="scope">
               <img 
               alt="用户头像" 
               style="width: 50px; height: 50px;">
            </template>
         </el-table-column>
         
         
         <el-table-column prop="operate" label="操作" width="180">
 
           <template slot-scope="scope">

            <div class="action-buttons">
            <span class="edit-link" @click="mod(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </span>

            <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.userId)" style="margin-left: 5px;">
             <template #reference>
              <span class="delete-link">
              <i class="el-icon-delete"></i> 删除
            </span>
             </template>
           </el-popconfirm>
          </div>

             <!-- <el-button size="small" type="success" @click="mod(scope.row)">
              <i class="el-icon-edit"></i> 编辑
            </el-button>
           
           <el-popconfirm title="确定删除吗?" @confirm="handleDelete(scope.row.userId)" style="margin-left: 5px;">
             <template #reference>
               <el-button
                 size="small"
                 type="danger"
               >删除</el-button>
             </template>
           </el-popconfirm> -->

          </template>
         
 
         </el-table-column>
       </el-table>
<!--  
       <el-pagination
       @size-change="handleSizeChange"
       @current-change="handleCurrentChange"
       :current-page.sync="pageNum"
       :page-sizes="[5, 10, 20,30]"
       :page-size="pageSize"
       layout="total, sizes, prev, pager, next, jumper"
       :total="total"
       style="margin-top: 5px;">
     </el-pagination>
  -->
     
 
    <!-- 新增 -->
     <el-dialog
       title="提示"
       :visible.sync="centerDialogVisible"
       :before-close="handleClose"
       center>
       <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        
         <!-- <el-form-item label="名称">
          <el-col :span="20">
           <el-input v-model="form.name"></el-input>
          </el-col>
         </el-form-item> -->
 
        
         <el-form-item label="用户ID" prop="userId" style="display: none;">
          <el-col :span="20">
           <el-input v-model="form.userId"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="用户名" prop="userName">
          <el-col :span="20">
           <el-input v-model="form.userName"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="电话号码" prop="telephone">
          <el-col :span="20">
           <el-input v-model="form.telephone"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="状态" prop="status">
          <el-col :span="20">
           <el-input v-model="form.status"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="角色名" prop="roleIdList">
          <el-select v-model="form.roleIdList" multiple>
           <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId">
          </el-option>
        </el-select>
         </el-form-item>
 
         <el-form-item label="密码" prop="password">
          <el-col :span="20">
           <el-input v-model="form.password"></el-input>
          </el-col>
         </el-form-item>

         <el-form-item label="邮箱" prop="email">
          <el-col :span="20">
           <el-input v-model="form.email"></el-input>
          </el-col>
         </el-form-item>

         <el-form-item label="地址" prop="address">
          <el-col :span="20">
           <el-input v-model="form.address"></el-input>
          </el-col>
         </el-form-item>
        
       </el-form>
 
       <span slot="footer" class="dialog-footer">
         <el-button @click="centerDialogVisible = false">取消</el-button>
         <el-button type="primary" @click="save">确定</el-button>
       </span>
     </el-dialog>

     <!-- 修改 -->
     <el-dialog
       title="提示"
       :visible.sync="centerDialogVisible1"
       :before-close="handleClose"
       center>
       <el-form ref="form1" :rules="rules1" :model="form1" label-width="120px">
        
         <!-- <el-form-item label="名称">
          <el-col :span="20">
           <el-input v-model="form.name"></el-input>
          </el-col>
         </el-form-item> -->
 
        
         <el-form-item label="用户ID" prop="userId" style="display: none;">
          <el-col :span="20">
           <el-input v-model="form1.userId"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="用户名" prop="userName">
          <el-col :span="20">
           <el-input v-model="form1.userName"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="电话号码" prop="telephone">
          <el-col :span="20">
           <el-input v-model="form1.telephone"></el-input>
          </el-col>
         </el-form-item>
 
         <el-form-item label="状态" prop="status">
          <el-col :span="20">
            <el-select
               v-model="form1.status">
              <el-option value="启用">启用</el-option>
              <el-option value="禁用">禁用</el-option>
            </el-select>
          </el-col>
         </el-form-item>
 
         <el-form-item label="角色名" prop="previousRoles">
          <el-select v-model="form1.roleIdList" multiple>
           <el-option v-for="role in previousRoles" :key="role.roleId" :label="role.roleName" :value="role.roleId">
          </el-option>
        </el-select>
         </el-form-item>
 
         <el-form-item label="密码" prop="password">
          <el-col :span="20">
           <el-input v-model="form1.password"></el-input>
          </el-col>
         </el-form-item>

         <el-form-item label="邮箱" prop="email">
          <el-col :span="20">
           <el-input v-model="form1.email"></el-input>
          </el-col>
         </el-form-item>

         <el-form-item label="地址" prop="address">
          <el-col :span="20">
           <el-input v-model="form1.address"></el-input>
          </el-col>
         </el-form-item>
        
       </el-form>
 
       <span slot="footer" class="dialog-footer">
         <el-button @click="centerDialogVisible1 = false">取消</el-button>
         <el-button type="primary" @click="save1">确定</el-button>
       </span>
     </el-dialog>
 
 
  </div>
 </template>
 
 <script>
 export default {
   name: "Main",
   data() {
       return {
        userId:'',
         // 当前选框中的值
         sels: [],
         // 每页多少条
         pageSize:10,
         // 当前页
         pageNum:1,
         name:'',
         vendorName:'',
         selectedRoles:[],
         total:0,
         tableData: [{
          userId:1,
          userName:"丽丽",
          telephone:"11111111",
          status:"启用"
         }],
         centerDialogVisible: false,
         centerDialogVisible1: false,
         form:{
           userId:0,
           userName:'',
           telephone:'',
           status:'',
           roleIdList:[],// 存储用户当前选择的角色信息
           password:'',
           email:'',
           address:''
         },
         roleOptions:[],// 存储所有角色选项的数组
         previousRoles:[],// 存储用户之前的角色信息
         form1:{
           userId:0,
           userName:'',
           telephone:'',
           status:'',
           roleIdList: [], // 存储用户之前的角色信息
           password:'',
           email:'',
           address:''
         },
         previousRolesOptions: [], // 存储用户之前的角色选项
         rules: {
          userId: [
               { required: true, message: '请输入用户ID', trigger: 'blur' },
              //  { min: 1, max: 5, message: '长度在1到8个字符', trigger: 'blur' },
           ],
           userName:[
           { required: true, message: '请输入用户名', trigger: 'blur' },
           ],
           telephone:[
           { required: true, message: '请输入电话号码', trigger: 'blur' },
           ],
           status:[
           { required: true, message: '请输入状态', trigger: 'blur' },
           ],
           roleIdList:[
           { required: true, message: '请输入角色ID', trigger: 'blur' },
           ],
           password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
           ],
           email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           ],
           address:[
           { required: true, message: '请输入地址', trigger: 'blur' },
           ],
           
          //  inType:[
          //      { required: true, message: '请输入入库类型', trigger: 'blur' },
          //      { min: 1, max: 5, message: '长度在3到8个字符', trigger: 'blur' },
          //  ],
           number:[
               { required: true, message: '请输入数量', trigger: 'blur' },
               { min: 1, max: 5, message: '长度在3到8个字符', trigger: 'blur' },
           ],
           usage:[
               { required: true, message: '请输入用途', trigger: 'blur' },
           ]
         },


         rules1: {
          userId: [
               { required: true, message: '请输入用户ID', trigger: 'blur' },
              //  { min: 1, max: 5, message: '长度在1到8个字符', trigger: 'blur' },
           ],
           userName:[
           { required: true, message: '请输入用户名', trigger: 'blur' },
           ],
           telephone:[
           { required: true, message: '请输入电话号码', trigger: 'blur' },
           ],
           status:[
           { required: true, message: '请输入状态', trigger: 'blur' },
           ],
           roleIdList:[
           { required: true, message: '请输入角色ID', trigger: 'blur' },
           ],
           password:[
           { required: true, message: '请输入密码', trigger: 'blur' },
           ],
           email:[
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           ],
           address:[
           { required: true, message: '请输入地址', trigger: 'blur' },
           ],
           
          //  inType:[
          //      { required: true, message: '请输入入库类型', trigger: 'blur' },
          //      { min: 1, max: 5, message: '长度在3到8个字符', trigger: 'blur' },
          //  ],
           number:[
               { required: true, message: '请输入数量', trigger: 'blur' },
               { min: 1, max: 5, message: '长度在3到8个字符', trigger: 'blur' },
           ],
           usage:[
               { required: true, message: '请输入用途', trigger: 'blur' },
           ]
         },
         
       }
     },
    // computed: {
    //   modifiedUserData(){
    //     return this.tableData.map(user =>{
    //       return{
    //         ...user,
    //        imgUrl:this.getUserAvatarUrl(user.imgUrl)
    //       }
    //     })
    //   }
    // },
    methods:{

      changeStatus(user){
        console.log(1111111+'user');
        console.log(user);
        const newStatus = user.status === '启用' ? '禁用':'启用'
        this.$confirm("确认改变状态吗？",{
          type:"warning"
        }).then(() =>{
          this.$axios.post(`/api/user/update/status?id=${user.userId}&status=${newStatus}`).then(res => {
          console.log(res);
          if(res.data.code == '200'){
            this.$message({
              type:"success",
              message:"修改成功"
            })   
            user.status = newStatus
            
          }else{
            this.$message({
              type:"error",
              message:"修改失败"
            })
          }
        })
        })
      },

      getStatusButtonClass(status) {
      if (status === '启用') {
        return 'primary';
      } else if (status === '禁用') {
        return 'danger';
      } else {
        return 'warning';
      }
    },
    //   getAvatarUrl(imgUrl) {
    //   return `/avatar/${imgUrl}`;
    // },
     // 重置表单
     resetForm(){
       this.$refs.form.resetFields();
     },
 
     // 当前页，每页几条发生改变时
     handleSizeChange(val) {
         this.pageNum = 1
         this.pageSize=val
         console.log(`${val} items per page`);
         this.loadPost()
       },
       handleCurrentChange(val) {
         // 设置当前页
         this.pageNum = val
         // 查询
         this.loadPost()
         console.log(`current page: ${val}`);
       },
      
     // 获取入库页面数据
     loadPost(){
       this.$axios.get('/api/user/list').then(res => {
         console.log(res);
         if(res.data.code == "200"){
           this.tableData = res.data.data
           this.total = res.data.data.total
         } 
 
       })
     },
 
     // 重置数据
     reset(){
       this.userId = ""
       this.loadPost()
     },
 
     // 新增
     add(){
       this.centerDialogVisible = true
       this.$nextTick(() => {
         this.resetForm();
       })
     },
     // 确认关闭模态框
     handleClose(done) {
         this.$confirm('Are you sure to close this dialog?')
           .then(_ => {
             done();
           })
           .catch(_ => {});
       },
     // 新增
     doSave(){
       this.$axios.post('/api/user/add',this.form
	     ).then(res => {
       console.log(res);
       if(res.data.code == "200"){
         this.loadPost();
         this.centerDialogVisible = false
         // alert("成功")
         this.$message({
           message: '更新成功',
           type: 'success'
         })
       } else{
         // alert("失败")
         this.$message({
           message:"操作失败",
           type:"error"
         })
       }
       })
     },
     // 修改
     doMod(){
       this.$axios.post("/api/user/update",this.form1).then(res => {
         console.log(res);
        if(res.data.code == '200'){
          this.centerDialogVisible1 = false
          this.loadPost()
          this.$message({
           message: '修改成功',
           type: 'success'
         })
        }else{
          this.$message({
           message:"修改失败",
           type:"error"
         })
        }
       })
     },
     save1(){
      this.doMod()
     },
     // 新增或者修改时时保存
     save(){
      this.doSave()
      //  this.$refs.form.validate((valid) => {
      //      if (valid) {
      //        if(this.form.userId){
      //          // 修改
      //          this.doMod()
      //        }else{
      //          // 新增
      //          this.doSave();
      //        }
      
      //      } else {
      //        console.log('error submit!!');
      //        return false;
      //      }
      //    });
 
       
     },
 
      // 删除
      handleDelete(id){
       console.log(id);
       this.$axios.delete("/api/user/delete/" + id).then(res => {

         console.log(res);
         if(res.data.code == '200'){
           this.$message({
           type:"success",
           message:"删除成功"
         })
         }else{
           this.$message({
           type:"error",
           message:"删除失败"
         })
         }
         this.loadPost()  // 删除之后重新加载表格的数据
 
       })
     },
 
     // 编辑
     mod(row){
       console.log(row);
       this.$axios.get("/api/user_role/list/" + row.userId).then((res) =>{
          console.log(123456);
          console.log(res);
          // this.previousRoles = res.data.data
          // this.selectedRoles = res.data.data.map(role => role.roleId)
          this.form1.roleIdList = res.data.data.map(role => role.roleId)
          console.log(this.form1.roleIdList);
        })
       // 先打开再异步处理
       this.centerDialogVisible1 = true
        console.log(row.userId);
       
       this.$nextTick(() => {
          // 赋值到表单
          this.form1.address = row.address
          this.form1.email = row.email
          this.form1.password = row.password
          this.form1.status = row.status
          this.form1.telephone = row.telephone
          this.form1.userId = row.userId
          this.form1.userName = row.userName
       })
     },
     // loadPost(){
     //   this.$axios.post('/api/in_warehouse/page',{
     //     "name": "扳手",
     //     "pageNo": 1,
     //     "pageSize": 8,
     //     "vendorName": ""
     //   }).then(res => {
     //     console.log(res);
     //   })
     // }

      // 批量删除
     // 获取选中的值
     handleSelectionChange(sels){
      this.sels = sels;
      console.log("选中的值",sels.map((item) => item.userId));
      
     },
     // 批量删除执行操作
     batchDelete(){
      // 删除的提示
      let count = this.sels.length;
      this.$confirm("确认删除这"+ count +"记录吗？","提示",{
        type:"warning"
      }).then(() => {
        // const idList = []
        // for(const v of this.sels){
        //   idList.push(v.id)
        // }
        // console.log(idList);
        let ids = this.sels.map((item) => item.userId)
        console.log(111222);
        // console.log(JSON.stringify(ids));
        console.log(ids);

        // 请求接口
        this.$axios.delete("/api/user/batch_delete/",
        { 
          data: ids, // 将数组数据作为请求体发送 
          headers: { 'Content-Type': 'application/json' } 
        }
        
        ).then(res =>{
          console.log(res);
          if(res.data.code == '200'){
            this.$message({
            message:"批量删除成功",
            type:"success"
          })
          }else{
            this.$message({
              message:"批量删除失败",
              type:"error"
            }).catch((e)=>{
              console.log(e);
            })
          }
          // console.log(1111);/*  */
          this.loadPost()
          // if(res.data.code == '200'){
          //   this.$message({
          //   message: "删除成功",
          //   type: "success"
          // })
          //   this.loadPost()
          // }else{
          //   this.$message({
          //     message:"删除失败",
          //     type:"error"
          //   })
          // }
         
        })
      }).catch((e) =>{
        console.log(e);
      })
     },
      // 设置唯一的row-key
      getRowKeyOfTarget(row) {
      return row.userId
        },

      // 根据用户id进行查询
      queryData(){
        if(this.userId == ''){
          this.loadPost()
        }else{
          this.$axios.get("/api/user/list/" + this.userId).then((res) => {
          if(res.data.code == '200'){
            this.tableData = []
            // 请求成功时将用户信息添加到tableData数组
            this.tableData.push(res.data.data)
            this.userId = ''
            this.$message({
              type:"success",
              message:"查询成功"
            })
          }else{
            this.$message({
              type:"error",
              message:"查询失败"
            })
          }
            
        })
        }
        
      },
      getRole(){
        this.$axios.get("/api/role/list"
        ).then((res) =>{
          console.log(res);
          // this.roleOptions.push(res.data.data.roleId)
          this.roleOptions = res.data.data
          this.previousRoles = res.data.data
          console.log(111);
          console.log(this.roleOptions);
        })
      },
      
      getAvatarImageUrl(avatarName) {
      // 假设头像图片存放在 /avatars 目录下
      return `/avatars/${avatarName}`;
    },

     },

      
   beforeMount() {
     this.loadPost()
     console.log(11111111111);
     this.getRole()
   }
 }
 </script>
 
 <style scoped>
    /* 将编辑和删除按钮放在同一行 */
    .action-buttons {
       display: flex;
       align-items: center;
       justify-content: center; /* 让子元素水平居中 */
    }

   .edit-link,
   .delete-link {
       color: #6699CC;
       text-decoration: underline;
       cursor: pointer;
       margin-right: 10px;
   }

   .edit-link:hover,
   .delete-link:hover {
      color: #99CCFF;
   }
 </style>